<?php

namespace app\common\dao\property\auth;

use app\common\dao\BaseDao;
use app\common\model\property\auth\PropertyAuthAccessModel;

class PropertyAuthAccessDao extends BaseDao
{

    /**
     * @return PropertyAuthAccessModel
     */
    protected function getModel(): string
    {
        return PropertyAuthAccessModel::class;
    }


    public function search(array $where, int $propertyId = null)
    {
        return $this->getModel()::getDB()
            ->when($propertyId !== null, function ($query) use ($propertyId) {
                $query->where('property_id', $propertyId);
            })
            ->when(isset($where['user_id']) && $where['user_id'] !== '', function ($query) use ($where) {
                $query->where('user_id', (int)$where['user_id']);
            })
            ->when(isset($where['is_owner']) && $where['is_owner'] !== '', function ($query) use ($where) {
                $query->where('is_owner', (int)$where['is_owner']);
            })
            ->when(isset($where['keywords']) && $where['keywords'] !== '', function ($query) use ($where) {
                $query->whereIn('user_id', function ($query) use ($where) {
                    $query->name('users')->whereLike('username|account||mobile|remark', '%' . $where['keywords'] . '%')->field('id');
                });
            })
            ->when(isset($where['add_time']) && $where['add_time'] !== '', function ($query) use ($where) {
                $this->timeSearchBuild($query, $where['add_time'], 'add_time');
            });
    }

    /**
     * 根据用户 ID 删除物业权限
     * @param int $userId
     * @return bool
     *
     * @author Amos
     * 2024-05-18 09:54
     */
    public function clearByAdminId(int $userId)
    {
        return $this->getSearch([
            'user_id' => $userId
        ])->delete();
    }

    /**
     * 根据物业 ID 删除权限
     * @param int $propertyId
     * @return bool
     *
     * @author Amos
     * 2024-05-18 09:54
     */
    public function clearPropertyId(int $propertyId)
    {
        return $this->getSearch([
            'property_id' => $propertyId
        ])->delete();
    }

}
